package com.soft.javase.ch07;

/**
 * @author wangzhisen
 * @Desc TODO
 * @date 2025/4/28
 */
public class TryDemo2 {

    public static void main(String[] args) {
       // testCatch();
        System.out.println("-------------------");
        //testFinally();
        System.out.println("-------------------");
        System.out.println(testReturn());
    }

    //允许 try...catch
    public static void testCatch(){
        int i = 10;
        try{
            int j = i/0;
            System.out.println("j= "+j);
            System.out.println("try");
        }catch(ArithmeticException e){
            System.out.println("catch");
            System.out.println("出现数学异常："+e.getMessage());
        }catch(NullPointerException e){
            System.out.println("出现空指针异常："+e.getMessage());
        }
    }

    //允许 try...finally
    public static void testFinally(){
        int i = 10;
        try{
            int j = i/0;
            //上方出现异常，下方则不能执行
            System.out.println("j= "+j);
            System.out.println("try");
        }finally {
            System.out.println("finally");
        }
    }

    //try...catch...finally 中遇到return
    public static int testReturn(){
        int i = 20;
        int j = 0;
        try{
            j=i/0;
            System.out.println("try");
            return j;
        }catch(Exception e){
            j++;
            System.out.println("catch");
            return j;
        }finally {
            j+=2;
            System.out.println("finally");
        }
    }
}
